<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class ConversationMessage extends Model
{
    /**
     * Indicates if the model should be timestamped.
     *
     * @var bool
     */
    public $timestamps = false;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'session_id', 'sender_type', 'message', 'emotion_score',
        'response_time_ms', 'is_highlighted', 'highlight_type'
    ];

    /**
     * The attributes that should be cast to native types.
     *
     * @var array
     */
    protected $casts = [
        'is_highlighted' => 'boolean',
        'created_at' => 'datetime',
    ];

    /**
     * 所属训练会话关系
     */
    public function session()
    {
        return $this->belongsTo(TrainingSession::class, 'session_id');
    }

    /**
     * 检查是否为用户消息
     */
    public function isUserMessage()
    {
        return $this->sender_type === 'user';
    }

    /**
     * 检查是否为AI消息
     */
    public function isAIMessage()
    {
        return $this->sender_type === 'ai';
    }

    /**
     * 获取情绪等级文本
     */
    public function getEmotionLevelAttribute()
    {
        if ($this->emotion_score === null) {
            return '未知';
        }

        if ($this->emotion_score >= 80) {
            return '非常积极';
        } elseif ($this->emotion_score >= 60) {
            return '积极';
        } elseif ($this->emotion_score >= 40) {
            return '中性';
        } elseif ($this->emotion_score >= 20) {
            return '消极';
        } else {
            return '非常消极';
        }
    }

    /**
     * 获取高亮类型文本
     */
    public function getHighlightTextAttribute()
    {
        $types = [
            'best' => '最佳话术',
            'error' => '错误话术',
            'neutral' => '普通话术'
        ];

        return $types[$this->highlight_type] ?? '未标记';
    }

    /**
     * 作用域：用户消息
     */
    public function scopeUserMessages($query)
    {
        return $query->where('sender_type', 'user');
    }

    /**
     * 作用域：AI消息
     */
    public function scopeAIMessages($query)
    {
        return $query->where('sender_type', 'ai');
    }

    /**
     * 作用域：高亮消息
     */
    public function scopeHighlighted($query)
    {
        return $query->where('is_highlighted', true);
    }
}